package com.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.CallableStatement;

import com.microsoft.sqlserver.jdbc.SQLServerDataSource;

//import org.apache.log4j.Logger;

public class DataUtil {

	static Connection conn = null;
	// private static final Logger logger =
	// Logger.getLogger(DataUtil.class.getName());

	public static String URL = "jdbc:sqlserver://pc13\\aptech;databaseName=DefectManagementSystem";
	public static String USER_NAME = "sa";
	public static String PASSWORD = "aptech";

	private static void connect() {
		try {
			SQLServerDataSource ds = new SQLServerDataSource();
			ds.setURL(URL);
			ds.setUser(USER_NAME);
			ds.setPassword(PASSWORD);
			conn = ds.getConnection();
			
			//Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			//conn = DriverManager.getConnection(URL, USER_NAME, PASSWORD);
			
		} catch (Exception e) {
			e.printStackTrace();
			// logger.debug(e.getMessage());
		}
	}

	public static void disconnected() {
		try {
			if (conn != null) {
				conn.close();
				conn = null;
			}

		} catch (Exception e) {
			e.printStackTrace();
			// logger.debug(e.getMessage());
		}
	}

	public static Connection getConnection() {
		connect();
		return conn;
	}

	public static int checkConnection() {

		try {
			if (conn != null) {
				return 0;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			// logger.debug(e.getMessage());
		}
		return 1;
	}

	public static ResultSet executeQuery(String sql) {
		try {
			connect();
			Statement statement = conn.createStatement();
			ResultSet rs = statement.executeQuery(sql);
			return rs;
		} catch (Exception e) {
			e.printStackTrace();
			// logger.debug(e.getMessage());
			return null;
		}
	}

	public static int executeUpdate(String sql) {
		try {
			connect();
			Statement statement = conn.createStatement();
			int rsUpdate = statement.executeUpdate(sql);
			return rsUpdate;
		} catch (Exception e) {
			e.printStackTrace();
			// logger.debug(e.getMessage());
			return 0;
		}
	}

	public static ResultSet executeStore(CallableStatement csmt) {

		try {

			connect();
			return csmt.executeQuery();
		} catch (Exception e) {
			e.printStackTrace();
			// logger.debug(e.getMessage());
		}
		return null;
	}

	public static int executeNonStore(CallableStatement csmt) {

		try {
			connect();
			csmt.execute();
			return 0;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			// logger.debug(e.getMessage());
			return 1;
		}
	}

}
